<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2019/8/29
 * Time: 14:35
 */

namespace Rain\Admin\Services\Business\Specific;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Rain\Admin\Services\Specification\Access;

Class AccessCard implements Access
{
    private $client;

    public function __construct()
    {
         $this -> client = App::make('AccessHttp');
    }

    public function login($username, $password)
    {
        $params = [
            'username' => $username,
            'password' => $password,
            'grant_type' => 'password'
        ];

        return $this -> requestClient($params, 600);
    }

    public function resetToken($refreshToken)
    {
        $params = [
            'refresh_token' => $refreshToken,
            'grant_type' => 'refresh_token'
        ];

        return $this -> requestClient($params, 611);
    }

    public function signOut()
    {
        $result = Auth::user() ? Auth::user() -> token() -> delete() : '';

        return true === $result ? echoArr(200) : echoArr(700);
    }

    /**
     * 请求 passport
     *
     * @param $params
     * @param $code
     * @return array
     */
    private function requestClient($params, $code){
        $params = array_merge([
            'client_id' => 3,
            'client_secret' => 'xRUIt2qZm9z4nDiJxMYwqx99IrjIeEdTkfDtot32',
            'scope' => '*'
        ], $params);

        try{
            $response = $this -> client -> post(url('oauth/token'), [
                'form_params' => $params
            ]);
        } catch (\Exception $exception) {
            return echoArr($code);
        }

        return echoArr(200, '', json_decode($response -> getBody(), true));
    }
}
